package com.xoa.service.inv.impl;

import com.xoa.dao.crm.CustomerMapper;
import com.xoa.dao.crm.SupplierMapper;
import com.xoa.dao.inv.*;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.inv.*;
import com.xoa.model.users.Users;
import com.xoa.service.inv.RepaymentService;
import com.xoa.util.CookiesUtil;
import com.xoa.util.common.session.SessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class RepaymentServiceImpl implements RepaymentService {
    @Resource
    private CusRepaymentMapper cusRepaymentMapper;
    @Resource
    private SupplierMapper supplierMapper;
    @Resource
    private SupRepaymentMapper supRepaymentMapper;
    @Resource
    private OmShipmentMapper omShipmentMapper;
    @Resource
    private UsersMapper usersMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Resource
    private PoCommodityEnterMapper poCommodityEnterMapper;
    @Resource
    private ProductTypeMapper productTypeMapper;

    /**
     * 查询所有客户还款记录
     */
    public List<Repayment> selectCusPayment(Map<String, Object> map) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        List<Repayment> repayments = cusRepaymentMapper.selectAll(map);
        for (Repayment repayment : repayments
        ) {
            OmShipment omShipment = omShipmentMapper.selectByDocumentNo(repayment.getDocumentNo());
            repayment.setRepaymentTimeStr(format.format(repayment.getRepaymentTime()));
            repayment.setUserName(usersMapper.findUserByuid((repayment.getUserId())).getUserName());
            repayment.setCustomerName(customerMapper.selectByPrimaryKey(omShipment.getCustomerId()).getCustomerName());
            repayment.setShipmentDateStr(format.format(omShipment.getShipmentDate()));
            //商品大类名称
            if (repayment.getEnterId() != null) {
                PoCommodityEnter poCommodityEnter = poCommodityEnterMapper.selectByPrimaryKey(repayment.getEnterId());
                ProductType productType = productTypeMapper.selectByPrimaryKey(Integer.valueOf(poCommodityEnter.getProductType()));
                if (productType != null) {
                    repayment.setProductType(productType.getProductTypeName());
                }
            }
        }
        return repayments;
    }

    /**
     * 添加客户还款记录
     */
    @Override
    public int insertCusPayment(Repayment repayment) {
        //获取登录用户
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        repayment.setUserId(users.getUid());
        OmShipment omShipment = omShipmentMapper.selectByDocumentNo(repayment.getDocumentNo());
        double ShipmentArrears = omShipment.getShipmentArrears() - repayment.getRepaymentAmount();
        double ShipmentPaid = omShipment.getShipmentPaid() + repayment.getRepaymentAmount();
        Map<String, Object> maps = new HashMap<>();
        maps.put("shipmentArrears", ShipmentArrears);
        maps.put("shipmentPaid", ShipmentPaid);
        maps.put("documentNo", repayment.getDocumentNo());
        omShipmentMapper.updateByDocumentNo(maps);
        Date date = new Date();//当前日期---生成单据号的主要因素
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String timeStr = format.format(date);
        String stt = "HK";//固定前缀
        int newNumber = 00001;//自增编号
        String repaymentNo = "";
        if (repayment != null) {
            Map<String, Object> mapa = new HashMap<>();
            mapa.put("record", new Repayment());
            List<Repayment> list = cusRepaymentMapper.selectAll(mapa);
            if (list.size() > 0 && list != null) {
                if (list.get(0).getRepaymentNo() != null && !list.get(0).getRepaymentNo().isEmpty()) {
                    String str = list.get(0).getRepaymentNo().substring(10);
                    int newNo = Integer.parseInt(str) + 1;
                    String dtr = String.format("%05d", newNo);
                    repaymentNo = stt + timeStr + dtr;
                }
                repayment.setRepaymentNo(repaymentNo);
            } else {
                String dtr = String.format("%05d", newNumber);
                repaymentNo = stt + timeStr + dtr;
                repayment.setRepaymentNo(repaymentNo);
            }

        }
        return cusRepaymentMapper.insert(repayment);
    }

    /**
     * 根据主键id删除客户还款记录(逻辑删除)
     */
    @Override
    public int delCusPaymentById(Integer repaymentId) {
        return cusRepaymentMapper.deleteByPrimaryKey(repaymentId);
    }

    /**
     * 添加供货商还款记录
     */
    @Override
    public int insertSupPayment(SupRepayment supRepayment) {
        //获取登录用户
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        supRepayment.setUserId(users.getUid());
        PoCommodityEnter poCommodityEnter = poCommodityEnterMapper.selectByDocumentNo(supRepayment.getDocumentNo());
        double EnterArrears = poCommodityEnter.getEnterArrears() - supRepayment.getRepaymentAmount();
        double EnterPaid = poCommodityEnter.getEnterPaid() + supRepayment.getRepaymentAmount();
        Map<String, Object> maps = new HashMap<>();
        maps.put("EnterArrears", EnterArrears);
        maps.put("EnterPaid", EnterPaid);
        maps.put("documentNo", supRepayment.getDocumentNo());
        poCommodityEnterMapper.updateByDocumentNo(maps);
        Date date = new Date();//当前日期---生成单据号的主要因素
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String timeStr = format.format(date);
        String stt = "HK";//固定前缀
        int newNumber = 00001;//自增编号
        String repaymentNo = "";
        if (supRepayment != null) {
            Map<String, Object> mapa = new HashMap<>();
            mapa.put("record", new Repayment());
            List<SupRepayment> list = supRepaymentMapper.selectAll(mapa);
            if (list.size() > 0 && list != null) {
                if (list.get(0).getRepaymentNo() != null && !list.get(0).getRepaymentNo().isEmpty()) {
                    String str = list.get(0).getRepaymentNo().substring(10);
                    int newNo = Integer.parseInt(str) + 1;
                    String dtr = String.format("%05d", newNo);
                    repaymentNo = stt + timeStr + dtr;
                }
                supRepayment.setRepaymentNo(repaymentNo);
            } else {
                String dtr = String.format("%05d", newNumber);
                repaymentNo = stt + timeStr + dtr;
                supRepayment.setRepaymentNo(repaymentNo);
            }

        }
        return supRepaymentMapper.insert(supRepayment);
    }

    /**
     * 根据主键id删除供货商还款记录
     */
    @Override
    public int delSupPaymentById(Integer supRepaymentId) {
        return supRepaymentMapper.deleteByPrimaryKey(supRepaymentId);
    }

    /**
     * 查询供应商还款记录
     */
    @Override
    public List<SupRepayment> selectSupPayment(Map<String, Object> map) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        List<SupRepayment> list = supRepaymentMapper.selectAll(map);
        for (SupRepayment supRepayment:list
             ) {
            PoCommodityEnter poCommodityEnter = poCommodityEnterMapper.selectByDocumentNo(supRepayment.getDocumentNo());
            supRepayment.setEnterIndates(format.format(poCommodityEnter.getEnterIndate()));
            supRepayment.setUserName(usersMapper.findUserByuid((supRepayment.getUserId())).getUserName());
            supRepayment.setSupplierName( supplierMapper.selectByPrimaryKey(poCommodityEnter.getSupplierId()).getSupplierName());
            supRepayment.setRepaymentTimeStr(format.format(supRepayment.getRepaymentTime()));
        }
        return list;
    }

}
